﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClassFolio.Model;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;

namespace ClassFolio
{
	public sealed class Tools
	{
		/// <summary>
		/// Возвращает строку переданную в параметре inStr, обрезанную до указанной длины length
		/// </summary>
		/// <param name="inStr">Входная строка</param>
		/// <param name="length">Максимальная длина строки</param>
		/// <returns>Строка с длинной length</returns>
		public static string SubStr(string inStr, int length)
		{
			return inStr.Length > length ? inStr.Substring(0, length) : inStr;
		}

		/// <summary>
		/// Проверка строки на значение null, с учетом пробелов
		/// </summary>
		/// <param name="value">Входная строка</param>
		/// <returns>Результат проверки, если строка пуста - true</returns>
		public static bool IsStringMissing(string value)
		{
			return String.IsNullOrEmpty(value) || value.Trim() == String.Empty;
		}

		/// <summary>
		/// Получаем список пользователей системы
		/// </summary>
		/// <returns></returns>
		public static ComboBoxItemList GetUserList()
		{
			string usersFile = String.Format("{0}\\{1}", Adjustment.AppDir, "Users.adj");
			if (!Directory.Exists(Path.GetDirectoryName(usersFile)))
				Directory.CreateDirectory(Path.GetDirectoryName(usersFile));

			using (Stream stream = new FileStream(usersFile, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read))
            {
                IFormatter formatter = new BinaryFormatter();
				try
				{
					return (ComboBoxItemList)formatter.Deserialize(stream);
				}
				catch 
				{
                    // ComboBoxList не удалось восстановить из файла сериализации, создаем пустой лист
                    return new ComboBoxItemList().Add(new Model.ComboBoxItem(""));
				}
            }
		}

        /// <summary>
        /// Получаем список серверов для подключения
        /// </summary>
        /// <returns></returns>
        public static ComboBoxItemList GetServerList()
        {
            string serversFile = String.Format("{0}\\{1}", Adjustment.AppDir, "Servers.adj");
            if (!Directory.Exists(Path.GetDirectoryName(serversFile)))
                Directory.CreateDirectory(Path.GetDirectoryName(serversFile));

            using (Stream stream = new FileStream(serversFile, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read))
            {
                IFormatter formatter = new BinaryFormatter();
                try
                {
                    return (ComboBoxItemList)formatter.Deserialize(stream);
                }
                catch
                {
                    return new ComboBoxItemList().Add(new Model.ComboBoxItem(""));
                }
            }
        }

		/// <summary>
		/// Сохраняется список пользователей системы
		/// </summary>
		/// <param name="usersList"></param>
		public static void SaveUserList(ComboBoxItemList usersList)
		{
			string usersFile = String.Format("{0}\\{1}", Adjustment.AppDir, "Users.adj");
			if (!Directory.Exists(Path.GetDirectoryName(usersFile)))
				Directory.CreateDirectory(Path.GetDirectoryName(usersFile));

			IFormatter formatter = new BinaryFormatter();
			using (Stream stream = new FileStream(usersFile, FileMode.Create, FileAccess.Write, FileShare.None))
			{
				formatter.Serialize(stream, usersList);
			}
		}

        /// <summary>
        /// Сохраняется список серверов системы
        /// </summary>
        /// <param name="serverList"></param>
        public static void SaveServerList(ComboBoxItemList usersList)
        {
            string serverFile = String.Format("{0}\\{1}", Adjustment.AppDir, "Servers.adj");
            if (!Directory.Exists(Path.GetDirectoryName(serverFile)))
                Directory.CreateDirectory(Path.GetDirectoryName(serverFile));

            IFormatter formatter = new BinaryFormatter();
            using (Stream stream = new FileStream(serverFile, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                formatter.Serialize(stream, usersList);
            }
        }
        public static void ShowPopupComboBoxItemList(ComboBoxItemList itemsList, UIElement uiElement, SelectionChangedEventHandler eventHandler)
        {
            if (itemsList == null || uiElement == null)
                return;

            ListBox listBox = new ListBox()
            {
                Padding = new Thickness(10, 2, 2, 2),
                ItemsSource = itemsList.Items,
                DisplayMemberPath = "Name"
            };

            Popup popup = new Popup()
            {
                StaysOpen = false,
                Name = "ppLogin",
                AllowsTransparency = true,
                VerticalOffset = 3,
                PlacementTarget = uiElement,
                Placement = PlacementMode.Bottom,
                PopupAnimation = PopupAnimation.Fade,
                Child = listBox,
                IsOpen = true
            };

            listBox.SelectionChanged += new SelectionChangedEventHandler((object sender, SelectionChangedEventArgs args) =>
            { popup.IsOpen = false; });

            if (eventHandler != null)
                listBox.SelectionChanged += eventHandler;
        }

		#region Константы
		
		public static int DefaultRowCount = 10;
		
		#endregion

    }
}
